package Chuong04;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Bai_01 extends JFrame implements ActionListener{

	JLabel ltitle = new JLabel("TỔNG HAI SỐ");
	JLabel lblSo1 = new JLabel("Số thứ nhất:");
	JTextField txtSo1 = new JTextField();
	JLabel lblSo2 = new JLabel("Số thứ hai:");
	JTextField txtSo2 = new JTextField();
	JLabel lblKQ = new JLabel("Kết quả:");
	JTextField txtKQ = new JTextField();  

	JButton btnAdd = new JButton("Tổng");
	JButton bClear = new JButton("Xóa");
	JButton btnExit = new JButton("Thoát");
	
	JPanel p1, p2, p3, p4, p5;
	public Bai_01(){
		setSize(400, 250);
		setTitle("Bài 01 - Chương 04");
		btnAdd.addActionListener(this);
		bClear.addActionListener(this);
		btnExit.addActionListener(this);
		txtKQ.setEditable(false);
		
		p1= new JPanel();		
		ltitle.setFont(new Font(getName(), Font.BOLD, 24));
		p1.add(ltitle, BorderLayout.CENTER);
		
		p2 = new JPanel(); 
        p2.setLayout(new GridLayout(4,2));
        
        
        p2.add(lblSo1); p2.add(txtSo1); 
        p2.add(lblSo2); p2.add(txtSo2); 
        p2.add(lblKQ); p2.add(txtKQ);
        
        p3 = new JPanel(); 
        
        p4 = new JPanel();       
        p4.add(btnAdd);
        p4.add(bClear); 
        p2.add(p3); p2.add(p4);
       
        p5 = new JPanel();        
        p5.add(btnExit);
       
        Container container = getContentPane();
        container.add(p1, BorderLayout.NORTH);
        container.add(p2, BorderLayout.CENTER);
        container.add(p5, BorderLayout.SOUTH);
	}
	
	public static void main(String[] args) {
		Bai_01 frm = new Bai_01();
		frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frm.setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==btnExit){
			System.exit(0);
		}
		
		if(e.getSource()==btnAdd){
			try{
				int so1 = Integer.parseInt(txtSo1.getText());
				int so2 = Integer.parseInt(txtSo2.getText());
				int kq = so1 + so2;
				txtKQ.setText(String.valueOf(kq));
			}
			catch (Exception arg) {
				txtKQ.setText("Lỗi nhập liệu!");
			}
		}
		
		if(e.getSource()==bClear){
			txtSo1.setText("");
			txtSo2.setText("");
			txtKQ.setText("");
		}
		
	}

}
